package edu.dhbw.andar.sample;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

import android.os.AsyncTask;
import android.util.Log;

public class Client extends AsyncTask<String, Void, String>{

	private String SERVER_ADDRESS = "luderserver.csbnet.se";
	private int SERVER_PORT = 1337;
	
	private Socket _socket;
	private BufferedReader _in;
	PrintWriter _out;
	
	@Override
	protected String doInBackground(String... params) {
		try {
			InetAddress serverAddr = InetAddress.getByName(SERVER_ADDRESS);
			_socket = new Socket(serverAddr, SERVER_PORT);
			_in = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
			_out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(_socket
                    .getOutputStream())), true);
		} catch(SocketException e) {
			Log.d("Client", "fel i socket");
			e.printStackTrace();
		} catch (UnknownHostException e) {
			Log.d("Client", "fel i host");
			e.printStackTrace();
		} catch (IOException e) {
			Log.d("Client", "fel i io");
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(params.length == 1){
			try {
				return getVariable(params[0]);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		else if(params.length > 1){
			String key = params[0].substring(0, params[0].indexOf(" "));
			String value = params[0].substring(params[0].indexOf(" ") + 1);
			
			setVariable(key, value);
		}
		
		try {
			_socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void setVariable(String key, String value){
//		Log.d("Client", "Socket IP: " + _socket.getInetAddress());
//		Log.d("Client", "Setting " + key + " to " + value);
		write(key + " " + value);
	}
	
	public String getVariable(String key) throws IOException{
		write(key);
		String value = _in.readLine();
//		Log.d("Client", "Getting " + value + " from server.");
	    return value;
	}
	
	/** Send a message to the server*/
    private void write(String message){
    	try {
    		_out.println(message);
        } catch (Exception e) {
            Log.e("Client", "Error!", e);
        }
    }
}
